package com.android.kuai.zhuan.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.NumberPicker;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.kuai.zhuan.MyApplication;
import com.android.kuai.zhuan.R;
import com.android.kuai.zhuan.adapter.AppListAdapter;
import com.android.kuai.zhuan.bean.AppListBean;
import com.android.kuai.zhuan.bean.UpgradeBean;
import com.android.kuai.zhuan.bean.UserIdBean;
import com.android.kuai.zhuan.download.DownloadService;
import com.android.kuai.zhuan.retrofit.BaseApi;
import com.android.kuai.zhuan.retrofit.api.ApiInterface;
import com.android.kuai.zhuan.service.MainService;
import com.android.kuai.zhuan.utils.CommandExecution;
import com.android.kuai.zhuan.utils.CommonUtils;
import com.android.kuai.zhuan.utils.HmSharedPreferencesUtils;
import com.android.kuai.zhuan.utils.ScreenUtils;
import com.android.kuai.zhuan.widget.CommonPopupWindow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    GridView gridView;
    List<AppListBean.DataBean> appListData = new ArrayList<>();
    ArrayList<String> taskList = new ArrayList<>();
    ArrayList<String> appList = new ArrayList<>();
    AppListAdapter adapter;
    View layoutStartBtn;
    String currentSelectApp = "";
    int currentPosition = -1;
    TextView btnStart, userId;
    //private NumberProgressBar bnp;
    private ProgressDialog p;
    AppStatusReceiver appStatusReceiver;
    View aboutUs;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initData();
        //CommonUtils.getPackageCode(this, "com.jifen.qukan");
    }

    @Override
    protected void onStart() {
        super.onStart();
        registerReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (adapter != null) {
            adapter.setData(appListData);
        }
        updateStartBtnStatus();
    }

    private void initView() {
        gridView = findViewById(R.id.gv_app_list);
        gridView.setOnItemClickListener(itemClickListener);
        layoutStartBtn = findViewById(R.id.layout_btn);
        layoutStartBtn.setOnClickListener(this);
        btnStart = findViewById(R.id.btn_start);
        userId = findViewById(R.id.user_id);
        aboutUs = findViewById(R.id.about_us_layout);
        aboutUs.setOnClickListener(this);
    }

    private void initData() {
        adapter = new AppListAdapter(this, appListData);
        gridView.setAdapter(adapter);
        //checkAppVersion();
        getUserId();
        if (appListData.size() == 0) {
            getAppList();
        }
    }

    private void registerReceiver() {
        appStatusReceiver = new AppStatusReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
        filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        filter.addDataScheme("package");
        registerReceiver(appStatusReceiver, filter);
    }

    private void unRegisterReceiver() {
        if (appStatusReceiver != null) {
            unregisterReceiver(appStatusReceiver);
        }
    }

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            DownloadService.DownloadBinder binder = (DownloadService.DownloadBinder) service;
            DownloadService downloadService = binder.getService();

            //接口回调，下载进度
            downloadService.setOnProgressListener(new DownloadService.OnProgressListener() {
                @Override
                public void onProgress(float fraction) {
                    Log.i("leihuiming", "下载进度：" + fraction);
                    if (p != null) {
                        p.setProgress((int) (fraction * 100));
                    }
                }

                @Override
                public void onDownloadCompleted(final String filePaht) {
                    if (p != null) {
                        p.setMessage("下载完成，正在安装...");
                        p.setProgress(100);
                        new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                CommandExecution.execCommand("pm install -r " + filePaht, true);
                                unbindService(conn);
                            }
                        }.start();
                    }
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    //gridView item click event
    AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            currentSelectApp = appListData.get(position).getPackageX();
            Log.d("leihuiming", "currentSelectApp = " + currentSelectApp);
            currentPosition = position;
            if (CommonUtils.appIsAvilible(MainActivity.this, appListData.get(position).getPackageX())) {
                //showPopWindow();
                if (appListData.get(position).getTimes() >= 3) {
                    appListData.get(position).setTimes(0);
                } else {
                    appListData.get(position).setTimes(3);
                }
                updateTaskList();
                adapter.setData(appListData);
            } else {
                showProgressDialog(appListData.get(position).getName());
                Intent intent = new Intent(MainActivity.this, DownloadService.class);
                intent.putExtra(DownloadService.BUNDLE_KEY_DOWNLOAD_URL, appListData.get(position).getApk());
                bindService(intent, conn, Context.BIND_AUTO_CREATE);
            }
        }
    };

    private void showProgressDialog(String title) {
        p = new ProgressDialog(MainActivity.this);
        // 设置进度条风格，风格为长形
        p.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        // 设置ProgressDialog 标题
        p.setTitle(title);
        // 设置ProgressDialog 提示信息
        p.setMessage("正在下载中...");
        // 设置ProgressDialog 标题图标
        //p.setIcon(R.mipma);
        // 设置ProgressDialog 进度条进度
        p.setProgress(100);
        // 设置ProgressDialog 的进度条是否不明确
        p.setIndeterminate(false);
        // 设置ProgressDialog 是否可以按退回按键取消
        p.setCancelable(false);
        p.setCanceledOnTouchOutside(false);
        // 让ProgressDialog显示
        p.show();
    }

    /**
     * 获取app列表并显示在gridview
     */
    private void getAppList() {
        Map<String, Object> maps = new HashMap<>();
        maps.put("service", "getTaskList");
        maps.put("imei", CommonUtils.getPhoneImei());
        maps.put("width", ScreenUtils.getScreenWidth(this));
        maps.put("heigh", ScreenUtils.getScreenHeight(this));
        maps = MainService.appendParams(maps);
        //RetrofitServiceManager.getInstance().create(ApiInterface.class).getAppList(maps);
        BaseApi.request(BaseApi.createApi(ApiInterface.class).getAppList(maps), new BaseApi.IResponseListener<AppListBean>() {
            @Override
            public void onSuccess(AppListBean data) {
                Log.d("leihuiming", "json= " + MyApplication.mGson.toJson(data));
                appListData = data.getData();
                for (int i = 0; i < appListData.size(); i++) {
                    appList.add(appListData.get(i).getPackageX());
                    if (!CommonUtils.appIsAvilible(MainActivity.this, appListData.get(i).getPackageX())) {
                        appListData.get(i).setTimes(0);
                    }
                }
                adapter.setData(appListData);
                updateTaskList();
            }

            @Override
            public void onFail() {

            }
        });
    }

    private void getUserId() {
        Map<String, Object> maps = new HashMap<>();
        maps.put("service", "getInviteCode");
        maps.put("imei", CommonUtils.getPhoneImei());
        maps = MainService.appendParams(maps);
        BaseApi.request(BaseApi.createApi(ApiInterface.class).getUserId(maps), new BaseApi.IResponseListener<UserIdBean>() {
            @Override
            public void onSuccess(UserIdBean data) {
                Log.d("leihuiming", "getUserID = " + MyApplication.mGson.toJson(data));
                if (data != null && data.getCode() == 0) {
                    if (data.getData().size() > 0) {
                        userId.setText("ID: " + data.getData().get(0).getCode());
                    }
                }
            }

            @Override
            public void onFail() {

            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.layout_btn:
                btnStart.setText("正在赚钱中...");
                layoutStartBtn.setEnabled(false);
                intent = new Intent(this, MainService.class);
                intent.putExtra("command", "start");
                intent.putStringArrayListExtra("tasklist", taskList);
                startService(intent);
                HmSharedPreferencesUtils.setDataList("tasklist", taskList);
                break;
            case R.id.about_us_layout:
                intent = new Intent(this, AboutUsActivity.class);
                startActivity(intent);
                break;
            default:
                break;

        }
    }

    /**
     * 显示次数选择弹窗
     */
    private void showPopWindow() {
        CommonPopupWindow commonPopupWindow = new CommonPopupWindow(this, R.layout.popwindow_time_selector,
                ScreenUtils.getScreenWidth(this), 600) {
            ;

            @Override
            protected void initView() {
                View view = getContentView();
                final NumberPicker picker = view.findViewById(R.id.number_picker_count);
                //picker.setMinValue(1);
                picker.setMaxValue(5);
                //不循环滚动
                picker.setWrapSelectorWheel(false);
                ////设置不可编辑
                picker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
                TextView cancel = view.findViewById(R.id.btn_cancel);
                TextView confirm = view.findViewById(R.id.btn_confirm);
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getPopupWindow().dismiss();
                    }
                });
                confirm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int count = picker.getValue();
                        appListData.get(currentPosition).setTimes(count);
                        adapter.setData(appListData);
                        updateTaskList();
                        getPopupWindow().dismiss();
                    }
                });
                CommonUtils.setNumberPickerDivider(picker);
            }

            @Override
            protected void initEvent() {

            }
        };
        PopupWindow popupWindow = commonPopupWindow.getPopupWindow();
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        popupWindow.showAtLocation(findViewById(R.id.main_activity_layout), Gravity.BOTTOM, 0, 0);

    }

    /**
     * 更新任务列表 及 任务开始按钮状态
     */
    private void updateTaskList() {
        //taskList.clear();
        taskList.clear();
        for (AppListBean.DataBean bean : appListData) {
            if (bean.getTimes() > 0) {
                taskList.add(bean.getPackageX());
                Log.d("leihuiming", "applist = " + bean.getPackageX());
            }
        }
        Log.d("leihuiming", "updateTaskList taskList = " + taskList.size());

        updateStartBtnStatus();
    }

    private void updateStartBtnStatus() {
        if (MyApplication.isRunning) {
            btnStart.setText("正在赚钱中...");
            layoutStartBtn.setEnabled(false);
            btnStart.setTextColor(ContextCompat.getColor(this, R.color.btn_disable_font_color));
            btnStart.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.mipmap.icon_coin_disable), null, null, null);
            btnStart.setCompoundDrawablePadding(5);
        } else {
            btnStart.setText("开始赚钱");
            if (taskList.size() <= 0) {
                layoutStartBtn.setEnabled(false);
                btnStart.setTextColor(ContextCompat.getColor(this, R.color.btn_disable_font_color));
                btnStart.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.mipmap.icon_coin_disable), null, null, null);
                btnStart.setCompoundDrawablePadding(5);
            } else {
                layoutStartBtn.setEnabled(true);
                btnStart.setTextColor(ContextCompat.getColor(this, R.color.btn_enable_font_color));
                btnStart.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.mipmap.icon_coin_enable), null, null, null);
                btnStart.setCompoundDrawablePadding(5);
            }
        }
    }

    public class AppStatusReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("leihuiming", "action = " + intent.getAction());
            switch (intent.getAction()) {
                case Intent.ACTION_PACKAGE_ADDED:
                    String addPkgName = intent.getData().getSchemeSpecificPart();
                    Log.d("leihuiming", "add pkg name = " + addPkgName);
                    if (appList.contains(addPkgName)) {
                        if (p != null && p.isShowing()) {
                            p.dismiss();
                            Toast.makeText(context, "应用已安装成功，请登录试玩！", Toast.LENGTH_LONG).show();
                            CommonUtils.startApp(context, addPkgName);
                        }
                        if (adapter != null) {
                            adapter.setData(appListData);
                        }

                    }
                    break;
                case Intent.ACTION_PACKAGE_REMOVED:
                    String removePkgName = intent.getData().getSchemeSpecificPart();
                    if (adapter != null) {
                        adapter.setData(appListData);
                    }

                    List<String> newAppList = HmSharedPreferencesUtils.getDataList("tasklist");
                    if (newAppList != null && newAppList.size() > 0) {
                        if (newAppList.contains(removePkgName)) {
                            newAppList.remove(removePkgName);
                            HmSharedPreferencesUtils.setDataList("tasklist", newAppList);
                        }
                    }

                    break;
            }

        }
    }

    public void checkAppVersion() {
        Map<String, Object> maps = new HashMap<>();
        maps.put("service", "getAppVersion");
        maps.put("imei", CommonUtils.getPhoneImei());
        maps = MainService.appendParams(maps);
        BaseApi.request(BaseApi.createApi(ApiInterface.class).getAppVersion(maps), new BaseApi.IResponseListener<UpgradeBean>() {
            @Override
            public void onSuccess(UpgradeBean data) {
                if (data.getCode() == 0 && data.getData().size() > 0) {
                    if (!CommonUtils.getPackageCode(MainActivity.this, getPackageName()).equals(data.getData().get(0).getVersion())) {
                        Log.d("leihuiming", "版本号不一致");
                        showProgressDialog("发现新版本");
                        Intent intent = new Intent(MainActivity.this, DownloadService.class);
                        intent.putExtra(DownloadService.BUNDLE_KEY_DOWNLOAD_URL, data.getData().get(0).getUrl());
                        bindService(intent, conn, Context.BIND_AUTO_CREATE);
                    }
                }
            }

            @Override
            public void onFail() {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterReceiver();
    }
}
